package com.hongminzheng.openapi.controller;

import com.github.pagehelper.PageInfo;
import com.hongminzheng.openapi.bean.Result;
import com.hongminzheng.openapi.bean.TableData;
import com.hongminzheng.openapi.pojo.Customer;
import com.hongminzheng.openapi.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hmz
 * @version v1.0
 * @data 2020/09/27
 **/
@RestController
@RequestMapping("/customer")
public class CustomerController {
    /**
     * 创建服务层对象
     */
    @Autowired
    private CustomerService customerService;

    /**
     * 分页查询所有,获取所有用户
     * @param page
     * @param limit
     * @return customerTableData
     */
    @GetMapping("/page")
    public TableData<Customer> findLayuiPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,String username, Integer state){
        Customer customer=new Customer();
        customer.setUsername(username);
        customer.setState(state);

        TableData<Customer> customerTableData = new TableData<>();
        PageInfo<Customer> customerPageInfo = customerService.findPage(page, limit, customer);

        customerTableData.setCount(customerPageInfo.getTotal());
        customerTableData.setData(customerPageInfo.getList());
        return customerTableData;
    }

    /**
     * 增加
     * @param customer
     * @return
     */
    @PostMapping("/add")
    public Result insertCustomer(Customer customer){
        try {
            customerService.insert(customer);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            return new Result(false, "添加失败");
        }
    }

    /**
     * 更新
     * @param customer
     * @return
     */
    @RequestMapping("/update")
    public Result updateCustomer(Customer customer){
        try {
            customerService.updateByPrimaryKey(customer);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            return new Result(false, "更新失败");
        }
    }

    /**
     * 批量删除
     * @param customerList
     * @return
     */
    @PostMapping("/dels")
    public Result dels(@RequestBody List<Customer> customerList) {
        //创建返回对象
        Result result = new Result();
        //创建循环，调用删除方法
        customerList.forEach(customer -> {
            customerService.deleteByPrimaryKey(customer.getId());
        });
        result.setStatus(true);
        result.setMessage("批量删除成功");
        return result;
    }

}
